﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DAL
{
    /// <summary>
    /// 对数据库的基本操作
    /// </summary>
    public abstract class Base<T>
    {
        private string _tableName;
        private string _key;

        public Base(string table,string key)
        {
            _tableName = table;
            _key = key;
        }

        public abstract bool Insert(T entity);

        public abstract bool Update(T entity);

        public abstract T GetEntityById(int id);
        public abstract T GetEntityById(string id);

        /// <summary>
        /// 更具ID删除记录
        /// 默认连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(int id)
        {
            string sql = string.Format("delete from {0} where {1} = {2}", _tableName, _key, id);
            return MySQLHelper.ExecuteNonQuery(sql) == 1;
        }
        /// <summary>
        /// 更具ID删除记录
        /// 默认连接
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual bool Delete(string id)
        {
            string sql = string.Format("delete from {0} where {1} = @id", _tableName, _key);
            return MySQLHelper.ExecuteNonQuery(sql, new KeyValuePair<string, object>("id", id)) == 1;
        }
        /// <summary>
        /// 返回最后插入的ID
        /// </summary>
        /// <returns></returns>
        protected int GetLastInsertID()
        {
            return int.Parse(MySQLHelper.ExecuteScalar("SELECT LAST_INSERT_ID()"));
        }
        /// <summary>
        /// 生成参数
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        protected KeyValuePair<string, object> GetParams(string key, object value)
        {
            return new KeyValuePair<string, object>(key, value);
        }
    }
}
